package com.gimi.cloud.jimi.client.controller;


import com.gimi.cloud.jimi.client.service.UserService;
import com.gimi.cloud.jimi.client.service.userInfo.LbsLocationService;
import com.gimi.cloud.jimi.client.service.userInfo.YpActivityService;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.enums.ServiceNameConstants;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.JsonUtil;
import com.gimi.cloud.jimi.common.utils.RandomUtil;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.common.utils.reqhead.Response;
import com.gimi.cloud.jimi.common.utils.reqhead.Util;
import com.gimi.cloud.jimi.commonService.sms.SmsPortal;
import com.gimi.cloud.jimi.commonService.util.APILocationUtil;
import com.gimi.cloud.jimi.commonService.util.Global;
import com.gimi.cloud.jimi.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.jimi.dto.sys.HtmlDTO;
import com.gimi.cloud.jimi.dto.user.UserDTO;
import com.gimi.cloud.jimi.entity.user.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * create by xiankejin on 2017-10-13
 */
@RequestMapping("/user")
@RestController
public class UserController{
    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    private final UserService userService;
    private YpActivityService ypActivityService;
    private LbsLocationService lbsLocationService;
    private SysConfigDao configDao;

    // 上传OSS成功FLAG
    private final static int SUCCESSFLAG = 1;
    @Autowired
    public UserController(UserService userService,YpActivityService ypActivityService,LbsLocationService lbsLocationService,SysConfigDao configDao) {
        this.userService = userService;
        this.ypActivityService = ypActivityService;
        this.lbsLocationService = lbsLocationService;
        this.configDao = configDao;
    }

    /**
     * 获取验证码
     * @param userDTO
     * @param response
     */
    @RequestMapping(value = "/getUserRegisterCode")
    public void getUserRegisterCode(@RequestBody UserDTO userDTO, HttpServletResponse response) throws MsgException {
        logger.info("user:" + userDTO);
        Response resp = new Response();
        Boolean res = userService.redisFixedTimeSendCode(userDTO.getMobilePhone());
        if(res) {//判断60秒内不能再次发送
           throw new MsgException(ResponseCodeEnum.ACCESS_BARRED, ServiceNameConstants.REPEAT_SEND_CODE_INFO);
        }
        // 创建验证码
        String createCode = RandomUtil.getRandomNumString(6);
        logger.info("createCode>>>"+createCode);
        //发送验证码
//        userService.sendCode(AppCommons.REGISTER_CODE_MAP, user.getPhone(), createCode);
        String typeNid = SmsPortal.LOGIN_BY_PWDCODE;
        ResponseCodeEnum responseCodeEnum = userService.sendCode(userDTO.getMobilePhone(), createCode ,typeNid);
        resp.setResponseCode(responseCodeEnum);
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }

    /**
     * 获取忘记密码验证码
     * @param userDTO
     * @param response
     */
    @RequestMapping(value = "/getModifypasswordCode")
    public void getModifypasswordCode(@RequestBody UserDTO userDTO, HttpServletResponse response) throws MsgException {
        logger.info("user:" + userDTO);
        Response resp = new Response();

        User isUser = userService.getUserByMobilePhone(userDTO);

        if(isUser==null){
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        Boolean res = userService.redisFixedTimeSendModifypasswordCode(userDTO.getMobilePhone());
        if(res) {//判断60秒内不能再次发送
            throw new MsgException(ResponseCodeEnum.ACCESS_BARRED, ServiceNameConstants.REPEAT_SEND_CODE_INFO);
        }
        // 创建验证码
        String createCode = RandomUtil.getRandomNumString(6);
        logger.info("createCode===>"+createCode);
        //发送验证码
        String typeNid = SmsPortal.MODIFYPASSWORD_CODE;
        ResponseCodeEnum responseCodeEnum = userService.sendCode(userDTO.getMobilePhone(), createCode ,typeNid);
        resp.setResponseCode(responseCodeEnum);
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }

    /**
     * 发送用户lbs等数据
     * @param map
     * @param response
     */
    @RequestMapping(value = "/getInformation")
    public void getInformation(@RequestBody Map<String, String> map, HttpServletResponse response) throws MsgException {
        logger.info("user:" + map.get("userId"));
        Global.IP_THREADLOCAL.set(map.get("ip"));
        Integer userId = Integer.valueOf(map.get("userId"));// paramLong("userId");// 用户
        int appIdentify = StringUtil.isBlank(map.get("appIdentify")) ? 0 : Integer.valueOf(map.get("appIdentify"));// paramInt("appIdentify"); // app识别号
        String appVersion = map.get("appVersion");// paramString("appVersion");// app版本号
        double latitude = StringUtil.isBlank(map.get("latitude")) ? 0 : Double.parseDouble(map.get("latitude"));
        double longitude = StringUtil.isBlank(map.get("longitude")) ? 0 : Double.parseDouble(map.get("longitude"));
        String address = map.get("address");// paramString("address");// 位置


        String ip = Global.getIP();
        String uniqueInformation = map.get("uniqueInformation");// paramString("uniqueInformation");// 设备唯一信息
        String idfa = map.get("idfa");// paramString("idfa");// idfa信息 仅ios
        String unitType = map.get("unitType");// paramString("unitType");// 设备型号
        String operators = map.get("operators");// paramString("operators");// 运营商
        String channelId = map.get("channelId");// paramString("channelId");// 渠道id
        String appId = map.get("appId");// paramString("appId");// 应用标识
        int userAction = Integer.valueOf(map.get("userAction"));// paramInt("userAction");
        int saveType = Integer.valueOf(map.get("saveType"));// paramInt("saveType");//添加OR修改
        String ipLocation = APILocationUtil.getAddressByIp(ip,false);
//		logger.info("---------------ip:" + ip);
//		logger.info("---------------ipLocation:" + ipLocation);
//		logger.info("---------------118.122.120.136ip:" + APILocationUtil.getAddressByIp("118.122.120.136",false));
        ypActivityService.insertUserInformation(userId, appIdentify, appVersion, latitude, longitude, address, ip,
                uniqueInformation, idfa, unitType, operators, channelId, appId, userAction, saveType, ipLocation);
        lbsLocationService.insertLbsLocation(longitude, latitude); // 存储LBS数据 2016年12月26日
        Response resp = new Response();
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }

    /**
     * 获取注册协议
     * @param response
     */
    @RequestMapping(value = "/getRegistAgreement")
    public void getRegistAgreement(@RequestBody HtmlDTO htmlDTO, HttpServletResponse response) throws MsgException {
        Response resp = new Response();
        //配置文件中获取注册协议地址
        String result = configDao.getConfigByKey(htmlDTO.getType());
        resp.setRes_data(result);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }
}
